package com.bizoe.ldapcheck.service.impl;

import com.bizoe.ldapcheck.domain.CheckResult;
import com.bizoe.ldapcheck.service.userCheckService;
import org.springframework.stereotype.Service;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.util.Hashtable;

/**
 * Created by wangxinxin on 2018/6/13.
 */
@Service
public class userCheckServiceImpl implements userCheckService {
    private LdapContext ctx = null;


    public String userCheck(String host,String port,String dn,String password,String base){
        Hashtable<String,String> HashEnv = new Hashtable<String,String>();
        HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别(none,simple,strong)

//        String dn="cn=alex,ou=rws,dc=bizoe123,dc=com";

        HashEnv.put(Context.SECURITY_PRINCIPAL, dn); //AD的用户名
        HashEnv.put(Context.SECURITY_CREDENTIALS, password); //AD的密码
        HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
        HashEnv.put("com.sun.jndi.ldap.connect.timeout", "3000");//连接超时设置为3秒
        HashEnv.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);// 默认端口389
        try {
            ctx =  new InitialLdapContext(HashEnv, null);
            System.out.println("身份验证成功!");
            GetADInfo();
            return CheckResult.CHECK_SUCCESS.getMsg();
        } catch (AuthenticationException e) {
            System.out.println("身份验证失败!");
            e.printStackTrace();
            return CheckResult.CHECK_FAIL.getMsg();
        } catch (javax.naming.CommunicationException e) {
            System.out.println("AD域连接失败!");
            e.printStackTrace();
            return CheckResult.AD_CONNECT_FAIL.getMsg();
        } catch (Exception e) {
            System.out.println("身份验证未知异常!");
            e.printStackTrace();
            return CheckResult.CHECK_UNKONW_ERROR.getMsg();
        } finally{
            if(null!=ctx){
                try {
                    ctx.close();
                    ctx=null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }


    public String GetADInfo() {

        String result = "";
        try {
            // 域节点OU=zhongguo,DC=ld,DC=com
            String base = "OU=rws,DC=bizoe123,DC=com";
            // LDAP搜索过滤器类
             String searchFilter = "objectClass=user";
            // 创建搜索控制器
            SearchControls searchCtls = new SearchControls();
            // 设置搜索范围
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            // String returnedAtts[] = { "memberOf" }; // 定制返回属性
            // searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集 不设置则返回所有属性
            // 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
            @SuppressWarnings("rawtypes")
            NamingEnumeration answer = ctx.search(base, searchFilter, searchCtls);// Search for objects using the filter
            while (answer.hasMore()) {
                SearchResult result1 = (SearchResult) answer.next();
                System.err.println(result1.getName());
                NamingEnumeration<? extends Attribute> attrs = result1.getAttributes().getAll();
                while (attrs.hasMore()) {
                    Attribute attr = attrs.next();
                    System.out.println(attr.getID() + "  =  " + attr.get());
                }
                System.out.println("============");
            }
            System.out.println("************************************************");
        } catch (NamingException e) {
            e.printStackTrace();
            System.err.println("Throw Exception : " + e);
        }
        return result;
    }


}
